package com.example.content.fragment.detail

import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.example.content.PRODUCT_ID
import com.example.content.R
import com.example.content.databinding.FragmentPhotoDetailBinding
import com.example.content.ext.convertUrl
import com.example.content.fragment.BaseMvvmFragment
import com.example.content.manager.GlobalMgr
import com.example.content.viewmodule.DetailViewModel
import com.example.core.extensions.showToast
import com.github.chrisbanes.photoview.PhotoView
import com.gyf.immersionbar.ImmersionBar
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog

/**
 * Created by zhudongao
 * Desc
 * Date 2/6/21
 */
class PhotoDetailFragment : BaseMvvmFragment<FragmentPhotoDetailBinding, DetailViewModel>(),
    View.OnClickListener {

    private var totalSize = 0
    private var currentIndex = 0
    private val photoList = mutableListOf<String>()

    private var productId = -1

    override fun getViewModuleClass() = DetailViewModel::class.java

    override fun getLayoutId() = R.layout.fragment_photo_detail

    override fun initView() {

        ImmersionBar.with(this).statusBarDarkFont(false).init()

        arguments.let {
            if (it != null) {
                productId = it.getInt(PRODUCT_ID, -1)
            }
        }
    }

    private fun viewPageInit() {
        dataBinding.viewPager.adapter = ImagePagerAdapter()
        dataBinding.viewPager.currentItem = currentIndex
        dataBinding.photoIndex.text = "${currentIndex + 1}/${totalSize}"
    }

    override fun initListener() {
        dataBinding.backIcon.setOnClickListener(this)
        dataBinding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                val current = (position % totalSize) + 1
                dataBinding.photoIndex.text = "${current}/${totalSize}"
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
        viewModel.productInfoResult.observe(this, observer = {
            if (it.isNotEmpty()) {
                for (product in it) {
                    when (product.resource_type) {
                        1 -> {
                            //视频类型
                            dataBinding.viewPager.visibility = View.GONE
                            dataBinding.videoPlay.visibility = View.VISIBLE
                            val thumbImageView = ImageView(context)
                            context?.let { it1 ->
                                Glide.with(it1).load(product.cover?.convertUrl())
                                    .into(thumbImageView)
                            }
                            dataBinding.videoPlay.backButton.visibility = View.GONE
                            val options = GSYVideoOptionBuilder()
                            options.setIsTouchWiget(true)
                                .setRotateViewAuto(false)
                                .setLockLand(false)
                                .setAutoFullWithSize(false)
                                .setShowFullAnimation(false)
                                .setNeedLockFull(true)
                                .setUrl(if (product.resource_list.isNotEmpty()) product.resource_list[0].convertUrl() else "")
                                .setThumbImageView(thumbImageView)
                                .setCacheWithPlay(false)
                                .build(dataBinding.videoPlay)
                            dataBinding.videoPlay.fullscreenButton.setOnClickListener {
                                dataBinding.videoPlay.startWindowFullscreen(
                                    dataBinding.videoPlay.context,
                                    true,
                                    true
                                )
                            }
                        }
                        2 -> {
                            //图片类型
                            dataBinding.viewPager.visibility = View.VISIBLE
                            dataBinding.videoPlay.visibility = View.GONE
                            photoList.clear()
                            for (url in product.resource_list) {
                                photoList.add(url.convertUrl())
                            }
                            totalSize = photoList.size
                            viewPageInit()
                        }
                    }
                    dataBinding.photoDesc.text = product.description
                }
            }
        })
        dataBinding.deleteProduct.setOnClickListener {
            context?.let { MaterialDialog.Builder(it)
                .content("是否要删除该作品?")
                .positiveText("是")
                .negativeText("否")
                .onPositive { _, _ ->
                    viewModel.deleteProductById(productId)
                }
                .show()
            }
        }
        viewModel.deleteResult.observe(this, observer = {
            if (it) {
                activity?.finish()
                GlobalMgr.productDel.postValue(true)
            } else {
                context?.showToast("删除失败")
            }
        })
    }

    override fun queryData() {
        viewModel.getProductInfoById(listOf(productId))
    }

    inner class ImagePagerAdapter : PagerAdapter() {
        override fun getCount() = photoList.size

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val photoView = PhotoView(container.context)
            context?.let { Glide.with(it).load(photoList[position % totalSize]).into(photoView) }
            container.addView(photoView)
            return photoView
        }

        override fun isViewFromObject(view: View, `object`: Any) = view === `object`

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View?)
        }
    }

    companion object {
        @JvmStatic
        fun newInstance() = PhotoDetailFragment()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.back_icon -> {
                activity?.finish()
            }
        }
    }
}